package org.example.ychdp.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpSession;
import org.example.ychdp.entity.Admin;
import org.example.ychdp.entity.Concert;
import org.example.ychdp.entity.Order;
import org.example.ychdp.entity.User;
import org.example.ychdp.service.AdminService;
import org.example.ychdp.service.ConcertService;
import org.example.ychdp.service.OrderService;
import org.example.ychdp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RequestMapping("/admin")
@Controller
public class adminController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private ConcertService concertService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;

    @RequestMapping(value = "/helloAdmin")
    public String testAdminIndex() {
        return "admin/adminLogin";
    }

    @RequestMapping(value = "/index")
    public ModelAndView AdminIndex(HttpSession session) {
        if (session.getAttribute("admin") == null) {
            Map<String, Object> model = new HashMap<String, Object>();
            String errorMsg = "您未登录，请登录";
            model.put("errorMsg", errorMsg);
            ModelAndView modelAndView = new ModelAndView("admin/adminLogin", model);
            return modelAndView;
        }
        List<User> userList = userService.selectAllUser();
        List<Order> orderList = orderService.selectAllOrder();
        List<Concert> concertList = concertService.selectAllConcert();
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("activeMenuItem", "index");
        model.put("userL", userList);
        model.put("orderL", orderList);
        model.put("concertL", concertList);
        ModelAndView modelAndView = new ModelAndView("admin/adminIndex", model);
        return modelAndView;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView testAdminLogin(@RequestParam String adminusername, @RequestParam String adminpassword
            , HttpSession session, String captcha) {
        List<User> userList = userService.selectAllUser();
        List<Order> orderList = orderService.selectAllOrder();
        List<Concert> concertList = concertService.selectAllConcert();

        Map<String, Object> model = new HashMap<>();
        Admin admin = new Admin();
        admin.setAdminusername(adminusername);
        admin.setAdminpassword(adminpassword);
        Admin admin1 = adminService.selectAdminByName(admin);
        if (admin1 == null) {
            String errorMsg = "账号不存在";
            model.put("errorMsg", errorMsg);
            ModelAndView modelAndView = new ModelAndView("admin/adminLogin", model);
            return modelAndView;
        }
        if ((!Objects.equals(admin1.getAdminpassword(), admin.getAdminpassword()))) {
            String errorMsg = "密码错误";
            model.put("errorMsg", errorMsg);
            ModelAndView modelAndView = new ModelAndView("admin/adminLogin", model);
            return modelAndView;
        }

//        String Captcha = (String) session.getAttribute("captcha");
//        if (Captcha == null || !Captcha.equalsIgnoreCase(captcha)) {
//            String errorMsg = "验证码错误";
//            model.put("errorMsg",errorMsg);
//            ModelAndView modelAndView = new ModelAndView("admin/adminLogin",model);
//            return modelAndView;
//        }

        session.setAttribute("admin", admin1);
        model.put("userL", userList);
        model.put("orderL", orderList);
        model.put("concertL", concertList);
        ModelAndView modelAndView = new ModelAndView("admin/adminIndex", model);
        return modelAndView;
    }

    @RequestMapping(value = "adminPersonal")
    public String personal(Model model, HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            String errorMsg = "您未登录，请登录";
            model.addAttribute("errorMsg", errorMsg);
            return "admin/adminLogin";
        }
        model.addAttribute("admin", admin);
        model.addAttribute("activeMenuItem", "personalInfo");
        return "admin/adminPersonal";
    }

    @RequestMapping(value = "adminEdit")
    public String edit(Model model, HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        model.addAttribute("admin", admin);
        return "admin/editAdmin";
    }

    @RequestMapping("/adminUpdate")
    public String updateUser(@ModelAttribute Admin admin, @RequestParam("newPassword") String newPassword, HttpSession session, Model model) {
        if (newPassword != null) {
            admin.setAdminpassword(newPassword);  // 新密码不为空时才修改
        }
        int success = adminService.updateAdmin(admin);
        if (success != 0) {
            session.setAttribute("admin", admin); // 更新 session 中的用户信息
            model.addAttribute("message", "信息更新成功！");
            return "redirect:/admin/adminPersonal";
        } else {
            model.addAttribute("message", "信息更新失败，请重试！");
            return "redirect:/admin/adminEdit";
        }
    }

    @RequestMapping(value = "/userManage")
    public ModelAndView testUserManage(HttpSession session,
                                       @RequestParam(required = false, defaultValue = "1") Integer page,
                                       @RequestParam(required = false, defaultValue = "") String nickname,
                                       @RequestParam(required = false, defaultValue = "") String number) {
        if (session.getAttribute("admin") == null) {
            Map<String, Object> model = new HashMap<String, Object>();
            String errorMsg = "您未登录，请登录";
            model.put("errorMsg", errorMsg);
            ModelAndView modelAndView = new ModelAndView("admin/adminLogin", model);
            return modelAndView;
        } else {
            PageInfo<User> userSearchResult = userService.searchUser(page, nickname, number);
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("userSearchResult",userSearchResult);
            model.put("activeMenuItem", "userManage");
            ModelAndView modelAndView = new ModelAndView("admin/User/userManage", model);
            return modelAndView;
        }

    }

    @RequestMapping("/addUser")
    public String toInsertPage() {
        return "admin/User/addUser";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addStudent(User user, Model model) {
        if (userService.checkUsernameExists(user.getUsername())) {
            model.addAttribute("errorMsg", "用户名已存在，请重新输入！");
            return "admin/User/addUser";  // 返回显示错误信息的页面，这里假设名为addUserError.html
        }
        int i = userService.insertUser(user);
        return "redirect:userManage";
    }

    @RequestMapping("/deleteUser")
    public String deleteUser(@RequestParam("id") int id) {
        int i = userService.deleteUserById(id);
        return "redirect:userManage";
    }

    @RequestMapping(value = "/editUser", method = RequestMethod.GET)
    public String editUser(@RequestParam("id") int id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "admin/User/editUser";
    }

    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public String updateUser(User user) {
        userService.updateUser(user);
        return "redirect:userManage";
    }

}
